package com.bootdo.system.controller;

import com.bootdo.system.config.MD5Utils;
import com.bootdo.system.domain.BizhongDO;
import com.bootdo.system.domain.FindPassVO;
import com.bootdo.system.domain.FrontuserDO;
import com.bootdo.system.domain.JiaoyicelueDO;
import com.bootdo.system.service.BizhongService;
import com.bootdo.system.service.FrontuserService;
import com.bootdo.system.service.JiaoyicelueService;
import com.bootdo.system.service.SmstableService;
import com.bootdo.system.utils.HttpUtils;
import com.bootdo.system.utils.R;
import com.bootdo.system.utils.SMS;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

@Slf4j
@ResponseBody
@Controller
public class RegController {

    @Autowired
    private FrontuserService frontuserService;
    @Autowired
    private JiaoyicelueService jiaoyicelueService;
    @Autowired
    private BizhongService bizhongService;

    @Autowired
    private SMS sms;



    @Transactional(propagation = Propagation.REQUIRES_NEW)
    @GetMapping("/reg")
    public R reg(FrontuserDO user, HttpServletRequest request, HttpServletResponse response) {
        //1.检查用户名唯一
        FrontuserDO frontuserDO = frontuserService.getUserByUsername(user.getUsername());
        if (frontuserDO != null) {
            return R.error().put("regtip","用户名已存在");
        }
        //2.密码一致
        if (!user.getLoginpass().equals(user.getPassword2())) {
            return R.error().put("regtip","两次密码不一致");
        }
        //3.邀请码存在
        FrontuserDO yaoqinguser = frontuserService.getUserByyaoqingma(user.getYaoqingma());
        if (yaoqinguser == null) {
            return R.error().put("regtip","邀请码不存在");
        }
        //4.保存
        user.setLoginpass(MD5Utils.encrypt(user.getUsername(), user.getLoginpass()));
        user.setPaypass(MD5Utils.encrypt(user.getUsername(), user.getLoginpass()));
        user.setDianshu(BigDecimal.ZERO);
        user.setZichan(BigDecimal.ZERO);
        user.setYouxiaotime(0);
        user.setParentid(yaoqinguser.getUserid());
        user.setCreatetime(new Date());
        user.setYaoqingma(getYaoqingma());
        user.setTouxiang("/images/moren-touxiang.jpg");
        frontuserService.save(user);
        //5.sessiont   cookie
        request.getSession().setAttribute("user", user);
        //添加cookie
        HttpUtils.AddCookie(user.getLoginpass(), response);
        //新建交易策略
        log.info("检查用户" + user.getUsername() + "的货币策略");
        final List<BizhongDO> bizhongDOS = bizhongService.list(new HashMap<>());
        for (BizhongDO bizhong : bizhongDOS) {

            JiaoyicelueDO jiaoyicelueDO = new JiaoyicelueDO();
            jiaoyicelueDO.setUserid(user.getUserid());
            jiaoyicelueDO.setBizhongid(bizhong.getId());
            jiaoyicelueDO.setChicangjine(BigDecimal.ZERO);
            jiaoyicelueDO.setBucangcishu(0);
            jiaoyicelueDO.setZhangfu(BigDecimal.ZERO);
            jiaoyicelueDO.setFirstamount(new BigDecimal(50));//首单50u
            jiaoyicelueDO.setBeitoushangxian(7);//倍投上限7单
            jiaoyicelueDO.setZhiyingbili(new BigDecimal(0.013));//止盈比例1.3%
            jiaoyicelueDO.setZhiyinghuidiao(new BigDecimal(0.002));//止盈回调0.2%
            jiaoyicelueDO.setBucangdiefu(new BigDecimal(0.033));//补仓跌幅3.3%
            jiaoyicelueDO.setBucanghuidiao(new BigDecimal(0.003));//补仓回调0.3%
            jiaoyicelueDO.setXunhuantype(0);
            jiaoyicelueDO.setCeluestatus(0);
            jiaoyicelueDO.setChicangjunjia(BigDecimal.ZERO);
            jiaoyicelueDO.setChicangshuliang(BigDecimal.ZERO);

            jiaoyicelueService.save(jiaoyicelueDO);
            log.info("用户" + user.getUsername() + " 新货币策略保存 货币：" + bizhong.getBizhongname());

        }

        return R.ok().put("regtip","注册成功");
    }


    @GetMapping("/findpass")
    public R findpass(FindPassVO findPassVO, HttpServletRequest request, HttpServletResponse response) {
        //空数据
        if (StringUtils.isEmpty(findPassVO.getUsername()) ||
                StringUtils.isEmpty(findPassVO.getPhone()) ||
                StringUtils.isEmpty(findPassVO.getPhonecode()) ||
                StringUtils.isEmpty(findPassVO.getLoginpass()) ||
                StringUtils.isEmpty(findPassVO.getPassword2())) {

            return R.error().put("findtip","数据不可为空");
        }
        //两次密码
        if (!findPassVO.getLoginpass().equals(findPassVO.getPassword2())) {
            return R.error().put("findtip","两次密码不一致");
        }
        //手机验证码
        final Object phone = request.getSession().getAttribute("phone");
        if (phone == null || !phone.toString().equals(findPassVO.getPhonecode())) {
            return R.error().put("findtip","手机验证码不一致");
        }

        //用户存在
        final FrontuserDO userByUsername = frontuserService.getUserByUsernameAndPhone(findPassVO.getUsername(), findPassVO.getPhone());
        if (userByUsername == null) {
            return R.error().put("findtip","用户不存在");
        }

        userByUsername.setLoginpass(MD5Utils.encrypt(findPassVO.getUsername(), findPassVO.getLoginpass()));

        frontuserService.update(userByUsername);
        //5.sessiont   cookie
        request.getSession().setAttribute("user", userByUsername);
        //添加cookie
        HttpUtils.AddCookie(userByUsername.getLoginpass(), response);

        return R.ok().put("findtip","找回密码成功");
    }


    @GetMapping("/getCode")
    public R getCode( String phone,
                     String type,
                     HttpSession session) {

        if(phone!=null&&phone.indexOf("+")==-1){
            phone = "+"+phone.trim();
        }
        log.info("手机号="+phone);
        //放进session
        String randomCode = SMS.getRandomCode();
        session.setAttribute(type, randomCode);
        //发送短信
        String sendsms = sms.sendsms(phone, randomCode);

        return R.ok().put("data", sendsms);
    }


    public String getYaoqingma() {
        String linkNo = "";
        // 用字符数组的方式随机
        String model = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
        char[] m = model.toCharArray();
        for (int j = 0; j < 6; j++) {
            char c = m[(int) (Math.random() * 36)];
            // 保证六位随机数之间没有重复的
            if (linkNo.contains(String.valueOf(c))) {
                j--;
                continue;
            }
            linkNo = linkNo + c;
        }
        return linkNo;
    }


}
